package com.grape.utils;


import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.redisson.api.RBatch;
import org.redisson.api.RBucket;
import org.redisson.api.RBucketAsync;
import org.redisson.api.RedissonClient;

import java.time.Duration;

/**
 * redis 工具类
 *
 * @author  putao
 * @email   2628279194@qq.com
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class RedisUtils {

    private static final RedissonClient CLIENT = SpringUtil.getBean(RedissonClient.class);

//    /**
//     * 限流
//     *
//     * @param key          限流key
//     * @param rateType     限流类型
//     * @param rate         速率
//     * @param rateInterval 速率间隔
//     * @return -1 表示失败
//     */
//    public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval) {
//        RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);
//        rateLimiter.trySetRate(rateType, rate, rateInterval, RateIntervalUnit.SECONDS);
//        if (rateLimiter.tryAcquire()) {
//            return rateLimiter.availablePermits();
//        } else {
//            return -1L;
//        }
//    }

    /**
     * 获取客户端实例
     */
    public static RedissonClient getClient() {
        return CLIENT;
    }

    /**
     * 缓存基本的对象，保留当前对象 TTL 有效期
     * @param key       缓存的键值
     * @param value     缓存的值
     * @param isSaveTtl 是否保留TTL有效期(例如: set之前ttl剩余90 set之后还是为90)
     * @since Redis 6.X 以上使用 setAndKeepTTL 兼容 5.X 方案
     */
    public static <T> void setCacheObject(final String key, final T value, final boolean isSaveTtl) {
        RBucket<T> bucket = CLIENT.getBucket(key);
        if (isSaveTtl) {
            try {
                bucket.setAndKeepTTL(value);
            } catch (Exception e) {
                long timeToLive = bucket.remainTimeToLive();
                setCacheObject(key, value, Duration.ofMillis(timeToLive));
            }
        } else {
            bucket.set(value);
        }
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param duration 时间
     */
    public static <T> void setCacheObject(final String key, final T value, final Duration duration) {
        RBatch batch = CLIENT.createBatch();
        RBucketAsync<T> bucket = batch.getBucket(key);
        bucket.setAsync(value);
        bucket.expireAsync(duration);
        batch.execute();
    }

    /**
     * 设置有效时间
     * @param key       Redis键
     * @param duration  超时时间
     * @return          true=设置成功；false=设置失败
     */
    public static boolean expire(final String key, final Duration duration) {
        RBucket rBucket = CLIENT.getBucket(key);
        return rBucket.expire(duration);
    }

    /**
     * 获得缓存的基本对象。
     * @param key   缓存键值
     * @return      缓存键值对应的数据
     */
    public static <T> T getCacheObject(final String key) {
        RBucket<T> rBucket = CLIENT.getBucket(key);
        return rBucket.get();
    }

    /**
     * 删除单个对象
     * @param key   缓存的键值
     * @return      删除结果
     */
    public static boolean deleteObject(final String key) {
        return CLIENT.getBucket(key).delete();
    }
}
